package com.babyqiao.wallpaper.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.babyqiao.wallpaper.portal.dao.WallpaperAlbumPicMapper;
import com.babyqiao.wallpaper.portal.entity.WallpaperAlbum;
import com.babyqiao.wallpaper.portal.dao.WallpaperAlbumMapper;
import com.babyqiao.wallpaper.portal.entity.WallpaperAlbumPic;
import com.babyqiao.wallpaper.portal.entity.vo.AlbumResVO;
import com.babyqiao.wallpaper.portal.entity.vo.AlbumStatisVO;
import com.babyqiao.wallpaper.portal.service.IWallpaperAlbumService;
import com.babyqiao.wallpaper.portal.utils.common.RedisKeys;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 专辑表包含专辑信息 服务实现类
 * </p>
 *
 * @author QLZ
 * @since 2021-02-24
 */
@Service
public class WallpaperAlbumServiceImpl extends ServiceImpl<WallpaperAlbumMapper, WallpaperAlbum> implements IWallpaperAlbumService {

    @Autowired
    WallpaperAlbumPicMapper albumPicMapper;
    @Autowired
    WallpaperAlbumMapper albumMapper;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     *因为Spring Cache是基于切面的（基于AOP的动态代理实现的：
     * 即都在方法调用前后去获取方法的名称、参数、返回值，然后根据方法名称、参数生成缓存的key(自定义的key例外)，进行缓存），
     * 所以内部方法调用不会调用切面，导致缓存不生效
     *
     * 解决办法是使用@lazy和@Autowired注解实现自我注入，然后使用时用注解的实例代替this调用方法。
     * */
    @Lazy
    @Autowired
    WallpaperAlbumServiceImpl WallpaperCachedService;


    /***
     *根据标签分页查找专辑列表
     * @Author QLZ
     * @Date 2021/2/25
     * @param current : 当前页
     * @param current : 每页条数
     * @param tagId :
     @return: com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.babyqiao.wallpaper.portal.entity.vo.AlbumResVO>
     */
    @Cacheable(value = "AlbumContent", key = "#current+'-'+#root.args[2]", sync = true)
    @Override
    public List<AlbumResVO> findAlbumByTagId(Long current,Long limit, String tagId) {
        List<AlbumResVO> albumResVOPage =baseMapper.selectAlbumByTagId(current,limit,tagId);
        return albumResVOPage ;

    }

    /**
     * 根据专辑ID查询专辑图片
     *
     * @param albumId : 专辑ID
     * @Author QLZ
     * @Date 2021/2/25
     * @return: java.util.List<com.babyqiao.wallpaper.portal.entity.WallpaperAlbumPic>
     */

    @Override
    public List<WallpaperAlbumPic> findPicByAlbumIdService(String albumId) {
        //先增加专辑热度
       increaseAlbumHot(albumId);
        //再查询专辑图片信息
        return WallpaperCachedService.getWallpaperAlbumPics(albumId);
    }

    /***
     * 获得专辑专辑活跃数据
     * @Author QLZ
     * @Date 2021/2/25
     *  @param albumId : 专辑ID
     *  @return: com.babyqiao.wallpaper.portal.entity.vo.AlbumStatisVO
     */
    @Override
    public AlbumStatisVO findStatisByAlbumService(String albumId) {
        Boolean hasKey = redisTemplate.hasKey(RedisKeys.ALBUM_STATIS.getKey() + albumId);
        AlbumStatisVO vo=null;
        //如果没有key则说明未缓存过数据
        if(!hasKey){
            WallpaperAlbum wallpaperAlbum = albumMapper.selectById(albumId);
            vo=new AlbumStatisVO();
            vo.setAlbumId(wallpaperAlbum.getId());
            vo.setHot(Long.parseLong(wallpaperAlbum.getHot()));

        }else{
            String s = redisTemplate.opsForValue().get(RedisKeys.ALBUM_STATIS.getKey() + albumId);
            vo = JSONObject.parseObject(s, AlbumStatisVO.class);
        }
        return vo;
    }


    private AlbumStatisVO increaseAlbumHot(String albumId) {
        Boolean hasKey = redisTemplate.hasKey(RedisKeys.ALBUM_STATIS.getKey() + albumId);
        AlbumStatisVO vo=null;
        //如果没有key则说明未缓存过数据
        if(!hasKey){
            WallpaperAlbum wallpaperAlbum = albumMapper.selectById(albumId);
            vo=new AlbumStatisVO();
            vo.setAlbumId(wallpaperAlbum.getId());
            vo.setHot(Long.parseLong(wallpaperAlbum.getHot()));

        }else{
            String s = redisTemplate.opsForValue().get(RedisKeys.ALBUM_STATIS.getKey() + albumId);
            vo = JSONObject.parseObject(s, AlbumStatisVO.class);
        }
        vo.setHot(vo.getHot()+1);
        redisTemplate.opsForValue().set(RedisKeys.ALBUM_STATIS.getKey()+albumId,JSONObject.toJSONString(vo));
        return vo;
    }

    @Cacheable(value = "AlbumPicContent", key = "#root.args[0]", sync = true)
    public List<WallpaperAlbumPic> getWallpaperAlbumPics(String albumId) {
        System.out.println("未命中查询数据库。。。。。。");
        QueryWrapper<WallpaperAlbumPic> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("album_id",albumId);
        return albumPicMapper.selectList(queryWrapper);
    }


    /***
     *点赞/取消点赞
     * @Author QLZ
     * @Date 2021/2/26
     *  @param albumId : 专辑ID
     * @param userId: 用户ID
     *  @param value: 1->点赞，其他->取消点赞
     *  @return: boolean
     */
    @Override
    public boolean likeItService(String albumId,String userId,String value) {
        boolean var= "1".equals(value);
        return redisTemplate.opsForValue().setBit(RedisKeys.ALBUM_LIKE.getKey() + albumId, Long.parseLong(userId), var);
    }

    /***
     *获得用户对图片的点赞状态
     * @Author QLZ
     * @Date 2021/2/26
     * @param albumId : 专辑ID
     * @param userId : 用户ID
     @return: java.lang.Integer
     */
    @Override
    public Boolean getLikeItStatusService(String albumId, String userId) {

        Boolean bit = redisTemplate.opsForValue().getBit(RedisKeys.ALBUM_LIKE.getKey() + albumId, Long.parseLong(userId));
        return bit;
    }

    /**
     * 获得点赞总数
     *
     * @param albumId : 专辑ID
     * @Author QLZ
     * @Date 2021/2/28
     * @return: null
     */
    @Override
    public Long getLikeCountService(String albumId) {
        Boolean hasKey = redisTemplate.hasKey(RedisKeys.ALBUM_LIKE.getKey() + albumId);
        Long counts=null;
        if(hasKey){
            counts = redisTemplate.execute((RedisCallback<Long>) con -> {
                byte[] bytes = (RedisKeys.ALBUM_LIKE.getKey() + albumId).getBytes();
                Long aLong = con.bitCount(bytes);
                return aLong;
            });
        }else {
            WallpaperAlbum wallpaperAlbum = baseMapper.selectById(albumId);
            counts = Long.parseLong(wallpaperAlbum.getLikeIt()) ;

        }

        return  counts;
    }

    /**
     * 根据演员id查询专辑
     *
     * @param  current:当前页
     * @param  limit:每页显示条数
     * @param actorId : 演员id
     * @Author QLZ
     * @Date 2021/2/28
     * @return: java.util.List<com.babyqiao.wallpaper.portal.entity.vo.AlbumResVO>
     */
    @Override
    @Cacheable(value = "AlbumContent", key = "#current+'-'+#root.args[2]", sync = true)
    public List<AlbumResVO> findAlbumByActor(Long current,Long limit, String actorId) {
        return baseMapper.selectAlbumByActorId(current,limit,actorId);
    }



}
